import { MVC } from "../../framework/MVC";
import { Notifier } from "../../framework/Notifier";
import { ListenID } from "../../ListenID";
import { GameVoManager } from "../../manager/GameVoManager";
import { UIManager } from "../../framework/UIManager";
import { Common_UIPath, FunUnlockTipsData, GameFunID, GameFunUnlockType, Guide } from "../../common/Common_Define";
import { Const } from "../../config/Const";
import { Manager } from "../../manager/Manager";
import { AudioType } from "../../manager/AudioManager";
import { Time } from "../../framework/Time";
import { Util } from "../../utils/Util";
import { AlertManager, AlertType } from "../../alert/AlertManager";
import { Cfg } from "../../config/Cfg";
import { MenuController } from "./MenuController";
import { UIRole, UIRoleManager } from "../../component/UIRole";
import { SceneManager } from "../../manager/SceneManager";
import { CallID } from "../../CallID";
import MenuModel from "./MenuModel";
import EquipModel from "../equip/EquipModel";
import BoxModel from "../box/BoxModel";
import FunOpen from "../funopen/FunOpen";
import FunUnlockTipsController from "../tips/FunUnlockTips/FunUnlockTipsController";
import TechnologyModel from "../technology/TechnologyModel";
import GlobalData from "../../GlobalData";
import AdManager from "../../manager/AdManadgr";
import { QRCode } from "../../framework/QRCode/QRCode";
import { QRErrorCorrectLevel } from "../../framework/QRCode/QRConst";
import CaptureUtils from "../../utils/Capture";
import DouyinManager from "../../manager/DouyinManager";
import KuaishouManager from "../../manager/KuaishouManager";
import NetAdapter from "../../adpapter/NetAdapter";
import { RoleManager } from "../../manager/RoleManager";
import { PropertyVO } from "../equip/Property";
import DeviceManager from "../../manager/DeviceManager";

const { ccclass, property } = cc._decorator;
declare let wx;
let angle = 30;
let isSelectLevel = false;
@ccclass
export default class MenuView_IOS extends MVC.BaseView {

    @property(cc.Node)
    bottom: cc.Node = null;


    @property(cc.SpriteFrame)
    passSp: cc.SpriteFrame = null;

    @property(cc.SpriteFrame)
    nopassSp: cc.SpriteFrame = null;

    @property(cc.Button)
    btnStart: cc.Button = null;

    @property(cc.RichText)
    announceMsg: cc.RichText = null;

    @property(cc.Node)
    btnshop: cc.Node = null;

    @property(cc.Node)
    qrCodeBg: cc.Node = null;

    @property(cc.Node)
    qrCode: cc.Node = null;

    @property(cc.Node)
    qrCodeMask: cc.Node = null;

    @property(cc.Label)
    dailiidLabel: cc.Label = null;

    @property(cc.Sprite)
    avatar: cc.Sprite;

    @property(cc.Node)
    shareTip: cc.Node;

    @property(cc.Node)
    shareBtn: cc.Node;

    @property(cc.Node)
    btnRevenue: cc.Node;

    @property(cc.Node)
    btnFuli: cc.Node;

    public uiRole: UIRole = null;


    protected changeListener(enable: boolean): void {
        Notifier.changeListener(enable, ListenID.Game_OpenUIList, this.openUIList, this);
        Notifier.changeListener(enable, ListenID.Menu_ShowAnnounce, this.showAnnounce, this);
        Notifier.changeListener(enable, ListenID.Role_GetExp, this.onRoleExpGet, this);
    }
    /*
     * 打开界面回调，每次打开只调用一次
     */
    public onOpen(args: any): void {
        super.onOpen(args);

        BoxModel.getInstance.resetVideoTime();
        GameVoManager.getInstance.stateVo.viewIndex = Const.ViewMap.MainView;
        this.fixUI();
        Notifier.send(ListenID.GetShareTimes);         //获取今日分享次数

        Notifier.send(ListenID.Game_SetCurrencyVis, true);
        this.openUIList();
        //顶部货币UI
        // UIManager.Open(Common_UIPath.CurrencyUI, 0, MVC.eUILayer.PopupDown);
        // Notifier.send(ListenID.On_Open_Menu);

        this.setPersonInfo();
        this.shareTip.active = false;
        this.shareBtn.active = false;

        let property = Notifier.call(CallID.Equip_GetBodyEquipPro, 0) as PropertyVO;
        let baseAllHp = Math.ceil(property.getHp() + Const.NormalHp);
        GameVoManager.getInstance.myUserVo.baseAllHp = baseAllHp;

        let url = GameVoManager.getInstance.myUserVo.avatar_url;
        console.log("userData.avatar_url=====", url)
        Util.loadRemoteSf(url, this.avatar);
    }

    @property(cc.Label)
    private nick_name: cc.Label = null;

    public setPersonInfo() {
        UIManager.Open(Common_UIPath.FuliView, MVC.eTransition.Default, MVC.eUILayer.Panel);

        let roleVO = GameVoManager.getInstance.myUserVo;
        this.nick_name.string = Util.normalName(roleVO.nick_name, 3);
        let btnInfo = cc.find(`btnInfo`, this.node);
        if (btnInfo) {
            let prog = cc.find(`expProgressBar`, btnInfo);
            let bar = cc.find(`bar`, prog);
            let lblLevel = cc.find(`imgPro6/lblLevel`, prog);
            let curLv = roleVO.roleLv;
            let curExp = roleVO.curExp;
            let nextLvCfg = Cfg.RoleLevel.get(curLv + 1);
            let max = nextLvCfg ? nextLvCfg.exp : 1;
            max = max == 0 ? 1 : max;
            bar.getComponent(cc.Sprite).fillRange = curExp / max;
            lblLevel.getComponent(cc.Label).string = curLv + ``;
        }
    }

    onRoleExpGet() {
        this.setPersonInfo();
    }

    /** UI打开列表，一个个有顺序的打开 */
    public openList: Function[] = [];

    public openUIList() {
        let cb = this.openList.shift();
        cb && cb();
    }

    private bg: cc.Node = null;
    public fixUI() {
        let size = Notifier.call(CallID.Setting_GetRealDesignSize);
        this.bg = this.node.getChildByName("bg");
        if (this.bg) {
            Util.resizeNode(this.bg);
        }

        // 测试
        this.bottom.y = -size.height * 0.5;
    }

    // public getOffset(): number {
    //     let systemSize = wx.getSystemInfoSync();
    //     let designAspect = 720 / 1280;
    //     let designHeight = systemSize.windowWidth / designAspect;
    //     //高度黑边
    //     let offset = (systemSize.windowHeight - designHeight) * 0.5;
    //     return offset
    // }

    /*
     * 关闭界面回调，每次打开只调用一次
     */
    public onClose(): void {
        if (this._isClosed) return;
        super.onClose();
        UIRoleManager.recycleUIRole(this.uiRole);
        UIManager.Close(Common_UIPath.MenuUI);
        UIManager.Close(Common_UIPath.CurrencyUI);
        this.unscheduleAllCallbacks();
        Notifier.send(ListenID.Menu_Open, false);
        Notifier.send(ListenID.On_Close_Menu);
    }

    public onStartGame() {
        Manager.audio.playAudio(501);
        UIManager.Open(Common_UIPath.RevenueView, MVC.eTransition.Default, MVC.eUILayer.Panel);
    }

    public onOpenSettingView() {
        // Notifier.send(ListenID.Setting_Open);
        UIManager.Open(Common_UIPath.SettingView_IOS, MVC.eTransition.Scale);
        Manager.audio.playAudio(501, AudioType.UI)
    }

    public onOpenShop() {
        Notifier.send(ListenID.Log_Event, { event_name: "gunPage_access" });
        Notifier.send(ListenID.Shop_Open, 1);
        Manager.audio.playAudio(501, AudioType.UI);
    }


    public onOpenPersonInfo() {
        Notifier.send(ListenID.Person_OpenView);
        Manager.audio.playAudio(501, AudioType.UI);
    }

    public onAddGold() {
        Manager.audio.playAudio(501, AudioType.UI);
        UIManager.Open(Common_UIPath.ExchangeDiamondUI);
    }

    public onExchangePower() {
        Manager.audio.playAudio(501, AudioType.UI);
        UIManager.Open(Common_UIPath.ExchangePowerUI);
    }

    public onOpenMoreGold(target, customdata: number) {
        Manager.audio.playAudio(501, AudioType.UI);
        UIManager.Open(Common_UIPath.MoreGoldUI, MVC.eTransition.Scale, MVC.eUILayer.Popup, customdata, null, 1);
        Notifier.send(ListenID.Log_Event, { event_name: "home_moregold" });
    }


    public onOpenService() {
        Manager.audio.playAudio(501, AudioType.UI);
        UIManager.Open(Common_UIPath.InviteAndServiceUI, MVC.eTransition.Default, MVC.eUILayer.Tips, 0);
        // UIManager.Open(Common_UIPath.GetExtraReward);
    }

    update(dt) {

    }


    //底部商店按钮/推广收益
    public onOpenBoxView() {
        // UIManager.Close(Common_UIPath.FuliView);
        Manager.audio.playAudio(501);
        UIManager.Open(Common_UIPath.RevenueView, MVC.eTransition.Default, MVC.eUILayer.Panel);
    }
    //底部装备按钮 /福利页
    public onOpenEquipView() {
        UIManager.Close(Common_UIPath.RevenueView);
        Manager.audio.playAudio(501);
        UIManager.Open(Common_UIPath.FuliView, MVC.eTransition.Default, MVC.eUILayer.Panel);
    }

    public showAnnounce(str) {
        this.announceMsg.node.parent.parent.active = false;
        return;
        this.announceMsg.node.stopAllActions();
        this.announceMsg.string = "";
        this.announceMsg.string = str;
        this.announceMsg
        this.announceMsg.node.x = 191;
        this.announceMsg.node.runAction(cc.sequence(cc.moveBy(6.0, -this.announceMsg.node.width - 385, 0), cc.callFunc(() => {
            if (this.announceMsg && this.announceMsg.node.parent) this.announceMsg.node.parent.parent.active = false;
        })));
    }

    onShareClick() {
        if (Util.isDouyinGame()) {
            DouyinManager.inst.share(GlobalData.inst.uid);
            return;
        }
        if (Util.isKuaishouGame()) {
            KuaishouManager.inst.share(GlobalData.inst.uid);
            return;
        }
        this.qrCodeMask.active = true;
        this.qrCodeBg.active = true;
        this.dailiidLabel.string = GlobalData.inst.uid;
        var qrcode = new QRCode(-1, QRErrorCorrectLevel.H);
        let dataUrl = 'https://jyxb-server.ruishangkeji.cn/app/index_app.html' + '?agent_uid=' + GlobalData.inst.uid;
        qrcode.addData(dataUrl);
        qrcode.make();

        var ctx = this.qrCode.getComponent(cc.Graphics);
        ctx.fillColor = cc.Color.BLACK;

        var tileW = this.qrCode.width / qrcode.getModuleCount();
        var tileH = this.qrCode.height / qrcode.getModuleCount();

        // draw in the Graphics
        for (var row = 0; row < qrcode.getModuleCount(); row++) {
            for (var col = 0; col < qrcode.getModuleCount(); col++) {
                if (qrcode.isDark(row, col)) {
                    var w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW));
                    var h = (Math.ceil((row + 1) * tileW) - Math.floor(row * tileW));
                    ctx.rect(Math.round(col * tileW), Math.round(row * tileH), w, h);
                    ctx.fill();
                }
            }
        }
    }

    onWxShare() {
 
    }

    onCloseClick() {
        this.qrCodeMask.active = false
        this.qrCodeBg.active = false
    }


    //推广收益按钮
    onShowRevenue() {
        Manager.audio.playAudio(501);
        UIManager.Open(Common_UIPath.RevenueView, MVC.eTransition.Default, MVC.eUILayer.Panel);
    }

    //福利按钮
    onShowFuli() {
        Manager.audio.playAudio(501);
        UIManager.Open(Common_UIPath.FuliView, MVC.eTransition.Default, MVC.eUILayer.Panel);
    }

    onClickSetting() {
        Manager.audio.playAudio(501);
        Notifier.send(ListenID.Setting_Open);
    }
}
